package alsTelecom.Http;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.Base64InputStream;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import alsTelecom.Device.Excepciones;
import alsTelecom.Objects.Lugar;
import alsTelecom.Objects.Usuario;
import alsTelecom.Objects.Utils;

public class ConexionBanner 
{ 
	  /**
	   * Mensaje de error 
	   */
	  static String error;  
	  /**
	   * Coleccion de datos
	   */
	  static Vector vector;
	 /**
	 * Establece la conexion al url de la pagina web, utiliza conexion BIS
	 * luego codifica el archivo, y se obtiene la imagen
	 * @param url URL de la Pagina Web
	 * @return La imagen descargada
	 * @throws IOException Si existe problemas de Conexion
	 */
		public static EncodedImage getImage(String url) throws IOException {
	      HttpConnection connection = null;
	      InputStream inputStream = null;

	      try {         
	          connection = (HttpConnection) Connector.open(url+ConnectionString.getConnectionString(),Connector.READ_WRITE,true);
	          inputStream = connection.openInputStream();
	          byte[] responseData = new byte[10000];
	          int length = 0;
	          StringBuffer rawResponse = new StringBuffer();
	          while (-1 != (length = inputStream.read(responseData))) {
	              rawResponse.append(new String(responseData, 0, length));
	          }
	          int responseCode = connection.getResponseCode();
	          
	          if (responseCode != HttpConnection.HTTP_OK) {
	              throw new IOException("Invalid response code:" + responseCode);
	          }
	          String result = rawResponse.toString();
	          byte[] dataArray = result.getBytes();  
	          return EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
	      }
	      catch (Exception ex)
	      {
	    	  String mensaje = "Error Descargando Imagenes";
	    	  Excepciones.notifyException(1,mensaje,ex);
	    	  return EncodedImage.getEncodedImageResource("noticias24.gif");
	          
	      }
	      finally {
	          try {
	              inputStream.close();
	              inputStream = null;
	              connection.close();
	              connection = null;
	          }
	          catch(Exception e){}
	      }
		}	


	  public static void sendException(int id, String mensaje, String exception) {
			try{
		String serviceUrl = "http://www.controldeagenda.com/bb/server/server.php?wsdl"+ConnectionString.getConnectionString();
		String serviceNamespace = "http://www.controldeagenda.com/bb/server/"+ConnectionString.getConnectionString();
		String soapAction = "http://www.controldeagenda.com/bb/server/getExcepcion"+ConnectionString.getConnectionString();
		String methodName = "getExcepcion";
		SoapObject rpc = new SoapObject(serviceNamespace, methodName);
		rpc.addProperty("id", ""+id);
		rpc.addProperty("mensaje", mensaje);
		rpc.addProperty("excepcion", exception);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

		envelope.bodyOut = rpc;
		envelope.dotNet = true;
		envelope.encodingStyle = SoapSerializationEnvelope.ENC;

		HttpTransport ht = new HttpTransport(serviceUrl);
		ht.debug = true;
		ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 

		ht.call(soapAction, envelope);
		
		}
	    catch(Exception ex){
	    }
	}
	  /**
	   * 
	   * @return
	   */
	  private static boolean register() throws Exception{

			
			String serviceUrl = "http://www.controldeagenda.com/bb/server/server.php?wsdl"+ConnectionString.getConnectionString();
			String serviceNamespace = "http://www.controldeagenda.com/bb/server/"+ConnectionString.getConnectionString();
			String soapAction = "http://www.controldeagenda.com/bb/server/Register"+ConnectionString.getConnectionString();
			String methodName = "Register";
			
			SoapObject rpc = new SoapObject(serviceNamespace, methodName);
			
			String pin = Integer.toHexString(DeviceInfo.getDeviceId());
			rpc.addProperty("pin", pin);
			rpc.addProperty("so", DeviceInfo.getSoftwareVersion());
			String modelo = DeviceInfo.getDeviceName();
			if(modelo.length()<5){
				rpc.addProperty("modelo", modelo);
			}else{
				rpc.addProperty("modelo", modelo.substring(0,4));
			}

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.encodingStyle = SoapSerializationEnvelope.ENC;
			
			HttpTransport ht = new HttpTransport(serviceUrl);
			ht.debug = true;
			ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 
			
			ht.call(soapAction, envelope);
			
			if(envelope.getResponse() !=null){				
			Object s = (Object) envelope.getResponse();
			String resp = s.toString();
				if(resp.equals("true")){
					
					return true;
				}else{
					 
					 return false;
				}
			}else{
				
				return false;
			}
			
		
	}
	
	  public static EncodedImage getBanner(int zona,int categ) throws Exception{
			
				if(register()){
	            		String serviceUrl = "http://www.controldeagenda.com/bb/server/server.php?wsdl"+ConnectionString.getConnectionString();
	            		String serviceNamespace = "http://www.controldeagenda.com/bb/server/"+ConnectionString.getConnectionString();
	            		String soapAction = "http://www.controldeagenda.com/bb/server/getBanner"+ConnectionString.getConnectionString();
	            		String methodName = "getBanner";
	            		SoapObject rpc = new SoapObject(serviceNamespace, methodName);

	            		String pin = Integer.toHexString(DeviceInfo.getDeviceId());
	        			rpc.addProperty("pin", pin);
	        			rpc.addProperty("zona",""+zona);
	        			rpc.addProperty("categoria",""+categ);
	        			
	        			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

	            		envelope.bodyOut = rpc;
	            		envelope.dotNet = true;
	            		envelope.encodingStyle = SoapSerializationEnvelope.ENC;

	            		HttpTransport ht = new HttpTransport(serviceUrl);
	            		ht.debug = true;
	            		ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 

	            		ht.call(soapAction, envelope);
	            		if(envelope.getResponse() !=null){
	            		Object s = (Object) envelope.getResponse();
	            		
	        			String resp = s.toString();
	        			byte[] b = resp.getBytes();
	        			byte[] bs = Base64InputStream.decode(b,0,b.length);
	        			EncodedImage ei = EncodedImage.createEncodedImage(bs, 0,bs.length);
	        			
						    	        		
	        			return ei;
	            		}else{
	            			
	            			return null;
	            		}
			}else{
				// retorna aqui
				return null;
			}
			
		}
	  
	public static EncodedImage getBanner(int zona,int categ,int noticia,String titulo) throws Exception{
		
			if(register()){
            		String serviceUrl = "http://www.controldeagenda.com/bb/server/server.php?wsdl"+ConnectionString.getConnectionString();
            		String serviceNamespace = "http://www.controldeagenda.com/bb/server/"+ConnectionString.getConnectionString();
            		String soapAction = "http://www.controldeagenda.com/bb/server/getBanner1"+ConnectionString.getConnectionString();
            		String methodName = "getBanner1";
            		SoapObject rpc = new SoapObject(serviceNamespace, methodName);
            		String pin = Integer.toHexString(DeviceInfo.getDeviceId());
            		rpc.addProperty("pin", pin);
        			rpc.addProperty("zona",""+zona);
        			categ++;
        			rpc.addProperty("categoria",""+categ);
        			rpc.addProperty("noticia",""+noticia);
        			rpc.addProperty("titulo",titulo);
        			
        			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            		envelope.bodyOut = rpc;
            		envelope.dotNet = true;
            		envelope.encodingStyle = SoapSerializationEnvelope.ENC;

            		HttpTransport ht = new HttpTransport(serviceUrl);
            		ht.debug = true;
            		ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 

            		ht.call(soapAction, envelope);
            		if(envelope.getResponse() !=null){
            		Object s = (Object) envelope.getResponse();
            		
        			String resp = s.toString();
        			byte[] b = resp.getBytes();
        			byte[] bs = Base64InputStream.decode(b,0,b.length);
        			EncodedImage ei = EncodedImage.createEncodedImage(bs, 0,bs.length);
        			          		
        			return ei;
					}else{
		    			return null;
		    		}
		}else{
			return null;
		}
		
	}
	
	public static Lugar[] getLugares() throws Exception{
		
			if(register()){
            		String serviceUrl = "http://www.controldeagenda.com/bb/server/server.php?wsdl"+ConnectionString.getConnectionString();
            		String serviceNamespace = "http://www.controldeagenda.com/bb/server/"+ConnectionString.getConnectionString();
            		String soapAction = "http://www.controldeagenda.com/bb/server/getLugares"+ConnectionString.getConnectionString();
            		String methodName = "getLugares";
            		SoapObject rpc = new SoapObject(serviceNamespace, methodName);
            		
        			rpc.addProperty("id", "1");
        			
        			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            		envelope.bodyOut = rpc;
            		envelope.dotNet = true;
            		envelope.encodingStyle = SoapSerializationEnvelope.ENC;

            		HttpTransport ht = new HttpTransport(serviceUrl);
            		ht.debug = true;
            		ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 

            		ht.call(soapAction, envelope);
            		if(envelope.getResponse() !=null){
            		Vector result = new Vector();
        			result = (Vector) envelope.getResponse();
        			try{
        				return Utils.RetrieveLugaresFromSoap(result);
        			}catch(Exception e){
        				Dialog.alert("error: "+e.getMessage());
        				return null;
        			}
            		}else{
		    			return null;
		    		}
        			
		}else{
			Dialog.alert("error");
			return null;
		}
		
	}
	public static boolean sendUsuario(Usuario user) throws Exception{
		// TODO Auto-generated method stub
		
			String serviceUrl = "http://www.controldeagenda.com/bb/server/server.php?wsdl"+ConnectionString.getConnectionString();
			String serviceNamespace = "http://www.controldeagenda.com/bb/server/"+ConnectionString.getConnectionString();
			String soapAction = "http://www.controldeagenda.com/bb/server/Usuario"+ConnectionString.getConnectionString();
			String methodName = "Usuario";
			SoapObject rpc = new SoapObject(serviceNamespace, methodName);
			
			String pin = Integer.toHexString(DeviceInfo.getDeviceId());
			rpc.addProperty("pin", pin);
			rpc.addProperty("nombre", user.getNombre());
			rpc.addProperty("apellido",user.getApellido());
			rpc.addProperty("sexo",user.getSexo());
			rpc.addProperty("email",user.getEmail());
			rpc.addProperty("fecha",user.getDate());
			rpc.addProperty("ciudad",""+user.getCiudad());
			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.encodingStyle = SoapSerializationEnvelope.ENC;

			HttpTransport ht = new HttpTransport(serviceUrl);
			ht.debug = true;
			ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 

			ht.call(soapAction, envelope);
			
			if(envelope.getResponse() != null){
			Object s = (Object) envelope.getResponse();
			String resp = s.toString();
				if(resp.equals("true")){
					return true;
				}
			}
			return false;
	}

}
